﻿/*
 * @Autor: PK
 * @Date: 2022/01/03 10:30:SS
 */

using System.Configuration;
using System.Linq;
using System.Reflection;
using Fasterflect;
using Reminiscence.Collections;
using ShkSimulation.core.exceptions;

namespace ShkSimulation.desktop.setting.tools {

	internal class ConfigHelper {
		
		internal static T LoadConfig<T>(ApplicationSettingsBase settingsBase) where T: Config, new(){
			var properties = settingsBase.GetType().Properties(Flags.InstancePublic | Flags.DeclaredOnly);
			var defaultPropertiesDictionary = properties.ToDictionary(each => each.Name);
			var settingProperties = typeof(T).Properties(Flags.InstancePublic | Flags.DeclaredOnly);
			List<string> lackProperty = new List<string>();
			foreach (var propertyInfo in settingProperties) {
				if (!defaultPropertiesDictionary.ContainsKey(propertyInfo.Name)) {
					lackProperty.Add(propertyInfo.Name);
				}
			}
			if (lackProperty.Count > 0) {
				throw new SimulationInitException($"设置文件不全，缺以下设置属性：{string.Join(", ", lackProperty)}");
			}
			T simulationConfig = new T();
			foreach (var propertyInfo in settingProperties) {
				propertyInfo.SetValue(simulationConfig, settingsBase[propertyInfo.Name]);
			}
			return simulationConfig;
		}
		
		internal static void Save<T>(T config, ApplicationSettingsBase settingsBase) where T: Config, new() {
			var properties = settingsBase.GetType().Properties(Flags.InstancePublic | Flags.DeclaredOnly);
			var propertiesDictionary = properties.ToDictionary(each => each.Name);
			var settingProperties = config.GetType().Properties(Flags.InstancePublic | Flags.DeclaredOnly);
			foreach (var propertyInfo in settingProperties) {
				PropertyInfo property = propertiesDictionary[propertyInfo.Name];
				property.SetValue(settingsBase, propertyInfo.GetValue(config));
			}
			settingsBase.Save();
		}

	}

}